/**
 * 沈阳土地交易中心官网爬虫
 *  
 */
import {Base,Item} from '../base';
class sytdjyzx extends Base{
  constructor(){
      super();
      this.name='沈阳土地交易中心';
      this.enabled = true;
      this.encode = "utf-8";
      this.debug = false;
      this.timeout = 1000000;
      this.collection = "lnxm";
      this.collectionShowName="辽宁项目爬虫";
      this.keyField = "title";
  }
  getItems(pageIndex:number) {
    let num = pageIndex + 1;
    let url = `http://124.95.131.60:8889/list2.php?page=${num}`;
    (<any>this.spider).headers = {};
    let content = this.spider.getSync(url);
    let $ = this.cheerio.load(content);
    let result:Item [] = [];
    let that = this;
    let lt = $('table').last();
    try {
        $('table').not(lt).each(function (index, ele) {
            let title = $(ele).find('a').attr('title').trim();
            let uri = $(ele).find('a').attr('href');
            result = result.concat(that.getExtraItem(uri, title));
        });
    }
    catch (error) {
        console.error(error);
    }
    return result;
}
getExtraItem(url:string, title:string) {
    let result:Item [] = []; 
    let content = this.spider.getSync(url);
    let $ = this.cheerio.load(content);
    let first = $('#zoom tr').first();
    let second = $('#zoom tr').eq(1);
    let that = this;
    $('#zoom tr').not(first).not(second).each(function (index, ele) {
        let item = that.buildItem();
        let flag=false;
        let ff=null;
        second.find('td').each(function (index1, ele1) {
            if((<any>$(ele1).attr('colspan'))==2){
                flag=true;
            (<any>item)[$(ele1).find('font').text().trim()] = $(ele).find('td').eq(index1).find('font').text().trim()==undefined?'':$(ele).find('td').eq(index1).find('font').text().trim();
            ff=$(ele).find('td').eq(index1).find('font').text().trim();
            }else{
           if(flag==true){
            (<any>item)[$(ele1).find('font').text().trim()] = $(ele).find('td').eq(index1+1).find('font').text().trim()==undefined?'':$(ele).find('td').eq(index1+1).find('font').text().trim();
            ff=$(ele).find('td').eq(index1).find('font').text().trim();
           }else{
            (<any>item)[$(ele1).find('font').text().trim()] = $(ele).find('td').eq(index1).find('font').text().trim()==undefined?'': $(ele).find('td').eq(index1).find('font').text().trim();
            ff=$(ele).find('td').eq(index1).find('font').text().trim();
           }
            }
           
        });
        if(ff==undefined||ff==''||ff==null){
            //do nothing
        }else{
        (<any>item).url = url;
        item.source = that.name;
        item.title = title;
        result.push(item);
        }
        
    });
    return result;
}
  getPageCount ():number{
      return 35;
  }
}
module.exports=new sytdjyzx();